<template>
  <div class="animated-text-container" :style="{ fontSize: fontSize + 'px' }">
    <span 
      v-for="(char, index) in textChars" 
      :key="index"
      :class="['char', { 'active': animationType === 'scale' && currentCharIndex === index }]"
      :style="getCharStyle(index)"
    >
      {{ char === ' ' ? '\u00A0' : char }}
    </span>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'

// 定义组件属性
interface Props {
  text: string // 必填：要显示的文本
  fontSize?: number // 可选：基础文字尺寸，默认13px
  animationType?: 'shimmer' | 'scale' // 可选：动画类型，默认为流光效果
  animationSpeed?: number // 可选：动画速度，默认为1
}

const props = withDefaults(defineProps<Props>(), {
  fontSize: 13,
  animationType: 'shimmer',
  animationSpeed: 1
})

// 将文本转换为字符数组
const textChars = computed(() => {
  return props.text.split('')
})

// 当前激活的字符索引（用于轮流变大效果）
const currentCharIndex = ref(0)
let animationInterval: number | null = null

// 获取字符样式
const getCharStyle = (index: number) => {
  if (props.animationType === 'shimmer') {
    // 流光效果：每个字符有不同的动画延迟
    return {
      animationDelay: `${index * 0.15}s`,
      animationDuration: `${1.5 / props.animationSpeed}s`
    }
  }
  return {}
}

// 开始轮流变大动画
const startScaleAnimation = () => {
  if (animationInterval) {
    clearInterval(animationInterval)
  }
  
  animationInterval = window.setInterval(() => {
    currentCharIndex.value = (currentCharIndex.value + 1) % textChars.value.length
  }, 1000 / props.animationSpeed)
}

// 停止动画
const stopAnimation = () => {
  if (animationInterval) {
    clearInterval(animationInterval)
    animationInterval = null
  }
}

// 监听动画类型变化
watch(() => props.animationType, (newType) => {
  stopAnimation()
  if (newType === 'scale') {
    startScaleAnimation()
  }
}, { immediate: true })

// 监听文本变化
watch(() => props.text, () => {
  currentCharIndex.value = 0
  if (props.animationType === 'scale') {
    stopAnimation()
    startScaleAnimation()
  }
})

// 组件挂载时开始动画
onMounted(() => {
  if (props.animationType === 'scale') {
    startScaleAnimation()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  stopAnimation()
})
</script>

<style scoped>
.animated-text-container {
  display: inline-flex;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.char {
  display: inline-block;
  letter-spacing: 0.1em;
  transition: transform 0.3s ease;
}

/* 流光效果 - 文字顺序变大 */
.animated-text-container .char {
  animation: textWave 1.5s infinite;
  color: var(--text-primary);
}

@keyframes textWave {
  0% {
    transform: scale(1);
    color: var(--text-primary);
  }
  50% {
    transform: scale(1.3);
    color: rgba(24, 160, 88, 1);
    font-weight: bold;
  }
  100% {
    transform: scale(1);
    color: var(--text-primary);
  }
}

/* 轮流变大效果 */
.char.active {
  transform: scale(1.3);
  color: rgba(24, 160, 88, 1);
  font-weight: bold;
}
</style>